// 全局变量
let currentLatency = 0;
let advanceTime = 100;
let targetIp = '8.8.8.8';
let timeUpdateInterval;
let pingInterval;

// DOM元素
const elements = {
    localTime: document.getElementById('localTime'),
    localMs: document.getElementById('localMs'),
    targetTime: document.getElementById('targetTime'),
    targetMs: document.getElementById('targetMs'),
    delayValue: document.getElementById('delayValue'),
    targetIpInput: document.getElementById('targetIp'),
    pingBtn: document.getElementById('pingBtn'),
    advanceTimeInput: document.getElementById('advanceTime'),
    pinBtn: document.getElementById('pinBtn'),
    minimizeBtn: document.getElementById('minimizeBtn'),
    closeBtn: document.getElementById('closeBtn')
};

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    initializeApp();
    bindEvents();
    startTimeUpdate();
});

// 初始化应用
function initializeApp() {
    // 设置默认值
    elements.targetIpInput.value = targetIp;
    elements.advanceTimeInput.value = advanceTime;
    
    // 首次ping测试
    setTimeout(() => {
        pingTarget();
    }, 1000);
    
    // 定期ping测试（每30秒）
    pingInterval = setInterval(pingTarget, 30000);
}

// 绑定事件
function bindEvents() {
    // Ping按钮
    elements.pingBtn.addEventListener('click', pingTarget);
    
    // IP输入框回车
    elements.targetIpInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            targetIp = e.target.value.trim();
            pingTarget();
        }
    });
    
    // IP输入框失焦
    elements.targetIpInput.addEventListener('blur', (e) => {
        targetIp = e.target.value.trim();
    });
    
    // 提前量输入
    elements.advanceTimeInput.addEventListener('input', (e) => {
        advanceTime = parseInt(e.target.value) || 0;
    });
    
    // 窗口控制按钮
    elements.pinBtn.addEventListener('click', () => {
        window.electronAPI.toggleAlwaysOnTop();
    });
    
    elements.minimizeBtn.addEventListener('click', () => {
        window.electronAPI.minimizeWindow();
    });
    
    elements.closeBtn.addEventListener('click', () => {
        window.electronAPI.closeWindow();
    });
    
    // 拖拽功能
    let isDragging = false;
    let currentX;
    let currentY;
    let initialX;
    let initialY;
    let xOffset = 0;
    let yOffset = 0;
    
    const titleBar = document.querySelector('.title-bar');
    
    titleBar.addEventListener('mousedown', dragStart);
    document.addEventListener('mousemove', dragMove);
    document.addEventListener('mouseup', dragEnd);
}

// 开始时间更新
function startTimeUpdate() {
    timeUpdateInterval = setInterval(updateTime, 10); // 每10ms更新一次
}

// 更新时间显示
function updateTime() {
    const now = new Date();
    
    // 本地时间
    const localTimeStr = formatTime(now);
    const localMs = now.getMilliseconds();
    
    elements.localTime.textContent = localTimeStr;
    elements.localMs.textContent = `${localMs.toString().padStart(3, '0')}ms`;
    
    // 换算后时间（当前时间 + 延迟 + 提前量）
    const adjustedTime = new Date(now.getTime() + currentLatency + advanceTime);
    const adjustedTimeStr = formatTime(adjustedTime);
    const adjustedMs = adjustedTime.getMilliseconds();
    
    elements.targetTime.textContent = adjustedTimeStr;
    elements.targetMs.textContent = `${adjustedMs.toString().padStart(3, '0')}ms`;
}

// 格式化时间
function formatTime(date) {
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    const ms = Math.floor(date.getMilliseconds() / 10).toString().padStart(2, '0');
    
    return `${hours}:${minutes}:${seconds}.${ms}`;
}

// Ping目标IP
async function pingTarget() {
    if (!targetIp) {
        return;
    }
    
    // 更新UI状态
    elements.pingBtn.classList.add('loading');
    elements.pingBtn.disabled = true;
    
    try {
        const result = await window.electronAPI.pingTarget(targetIp);
        
        if (result.success) {
            currentLatency = Math.round(result.latency);
            elements.delayValue.textContent = `${currentLatency} ms`;
        } else {
            currentLatency = 0;
            elements.delayValue.textContent = '离线';
        }
    } catch (error) {
        currentLatency = 0;
        elements.delayValue.textContent = '错误';
    } finally {
        // 恢复按钮状态
        elements.pingBtn.classList.remove('loading');
        elements.pingBtn.disabled = false;
    }
}



// 拖拽功能
function dragStart(e) {
    initialX = e.clientX - xOffset;
    initialY = e.clientY - yOffset;
    
    if (e.target === document.querySelector('.title-bar') || 
        e.target.closest('.title-bar')) {
        isDragging = true;
    }
}

function dragMove(e) {
    if (isDragging) {
        e.preventDefault();
        currentX = e.clientX - initialX;
        currentY = e.clientY - initialY;
        
        xOffset = currentX;
        yOffset = currentY;
        
        document.body.style.transform = `translate3d(${currentX}px, ${currentY}px, 0)`;
    }
}

function dragEnd(e) {
    initialX = currentX;
    initialY = currentY;
    isDragging = false;
}

// 键盘快捷键
document.addEventListener('keydown', (e) => {
    // Ctrl+R 刷新ping
    if (e.ctrlKey && e.key === 'r') {
        e.preventDefault();
        pingTarget();
    }
    
    // ESC 隐藏窗口
    if (e.key === 'Escape') {
        window.electronAPI.closeWindow();
    }
    
    // F5 刷新ping
    if (e.key === 'F5') {
        e.preventDefault();
        pingTarget();
    }
});

// 精确计时器（用于更高精度的时间计算）
function getHighPrecisionTime() {
    return performance.now() + performance.timeOrigin;
}

// 导出函数供调试使用
window.timeApp = {
    pingTarget,
    updateTime,
    getHighPrecisionTime,
    getCurrentLatency: () => currentLatency,
    getAdvanceTime: () => advanceTime
}; 